package cn.jishiyu11.xeqb.webview

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.text.TextUtils
import android.util.Log

import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * Created by jsy_zj on 2017/10/17.
 */

object FileUtils {
    /**
     * 把图片压缩到200K
     *
     * @param oldpath
     * 压缩前的图片路径
     * @param newPath
     * 压缩后的图片路径
     * @return
     */
    fun compressFile(oldpath: String, newPath: String): File? {
        var compressBitmap: Bitmap? = FileUtils.decodeFile(oldpath)
        var newBitmap: Bitmap? = ratingImage(oldpath, compressBitmap)
        val os = ByteArrayOutputStream()
        newBitmap!!.compress(Bitmap.CompressFormat.PNG, 100, os)
        val bytes = os.toByteArray()

        var file: File? = null
        try {
            file = FileUtils.getFileFromBytes(bytes, newPath)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (newBitmap != null) {
                if (!newBitmap.isRecycled) {
                    newBitmap.recycle()
                }
                newBitmap = null
            }
            if (compressBitmap != null) {
                if (!compressBitmap.isRecycled) {
                    compressBitmap.recycle()
                }
                compressBitmap = null
            }
        }
        return file
    }

    private fun ratingImage(filePath: String, bitmap: Bitmap?): Bitmap {
        val degree = readPictureDegree(filePath)
        return rotaingImageView(degree, bitmap)
    }

    /**
     * 旋转图片
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    fun rotaingImageView(angle: Int, bitmap: Bitmap?): Bitmap {
        //旋转图片 动作
        val matrix = Matrix()
        matrix.postRotate(angle.toFloat())
        println("angle2=" + angle)
        // 创建新的图片
        return Bitmap.createBitmap(bitmap!!, 0, 0,
                bitmap.width, bitmap.height, matrix, true)
    }

    /**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    fun readPictureDegree(path: String): Int {
        var degree = 0
        try {
            val exifInterface = ExifInterface(path)
            val orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return degree
    }

    /**
     * 把字节数组保存为一个文件
     *
     * @param b
     * @param outputFile
     * @return
     */
    fun getFileFromBytes(b: ByteArray, outputFile: String): File? {
        var ret: File? = null
        var stream: BufferedOutputStream? = null
        try {
            ret = File(outputFile)
            val fstream = FileOutputStream(ret)
            stream = BufferedOutputStream(fstream)
            stream.write(b)
        } catch (e: Exception) {
            // log.error("helper:get file from byte process error!");
            e.printStackTrace()
        } finally {
            if (stream != null) {
                try {
                    stream.close()
                } catch (e: IOException) {
                    // log.error("helper:get file from byte process error!");
                    e.printStackTrace()
                }

            }
        }
        return ret
    }

    /**
     * 图片压缩
     *
     * @param fPath
     * @return
     */
    fun decodeFile(fPath: String): Bitmap {
        val opts = BitmapFactory.Options()
        opts.inJustDecodeBounds = true
        opts.inDither = false // Disable Dithering mode
        opts.inPurgeable = true // Tell to gc that whether it needs free
        opts.inInputShareable = true // Which kind of reference will be used to
        BitmapFactory.decodeFile(fPath, opts)
        val REQUIRED_SIZE = 400
        var scale = 1
        if (opts.outHeight > REQUIRED_SIZE || opts.outWidth > REQUIRED_SIZE) {
            val heightRatio = Math.round(opts.outHeight.toFloat() / REQUIRED_SIZE.toFloat())
            val widthRatio = Math.round(opts.outWidth.toFloat() / REQUIRED_SIZE.toFloat())
            scale = if (heightRatio < widthRatio) heightRatio else widthRatio//
        }
        Log.i("scale", "scal =" + scale)
        opts.inJustDecodeBounds = false
        opts.inSampleSize = scale
        return BitmapFactory.decodeFile(fPath, opts).copy(Bitmap.Config.ARGB_8888, false)
    }


    /**
     * 创建目录
     * @param path
     */
    fun setMkdir(path: String) {
        val file = File(path)
        if (!file.exists()) {
            file.mkdirs()
            Log.e("file", "目录不存在  创建目录    ")
        } else {
            Log.e("file", "目录存在")
        }
    }

    /**
     * 获取目录名称
     * @param url
     * @return FileName
     */
    fun getFileName(url: String): String? {
        val lastIndexStart = url.lastIndexOf("/")
        return if (lastIndexStart != -1) {
            url.substring(lastIndexStart + 1, url.length)
        } else {
            null
        }
    }

    /**
     * 删除该目录下的文件
     *
     * @param path
     */
    fun delFile(path: String) {
        if (!TextUtils.isEmpty(path)) {
            val file = File(path)
            if (file.exists()) {
                file.delete()
            }
        }
    }


}
